package com.pathfinder.providers;

import com.pathfinder.model.Game;
import com.pathfinder.utils.ClientUtils;
import org.json.JSONArray;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static com.pathfinder.model.Serialization.gameFromJson;

/**
 * Date: 08.05.11
 *
 * @author Victor Passichenko (vpas@yandex-team.ru)
 */
public class HttpGamesListProvider implements GamesListProvider {

    final static String GAME_LIST_URL = "http://pathfindersgame.appspot.com/game/list";
    
    public List<Game> getAvailableGames() {
        try {
            HttpURLConnection connection = openGetConnection(GAME_LIST_URL);
            String data = ClientUtils.getTextFromInputStream(connection.getInputStream());

//            Log.d("PATHFINDERS", "data from server: " + data);
            JSONArray gamesJsonArray = new JSONArray(data);
            List<Game> games = new ArrayList<Game>(gamesJsonArray.length());
            for (int i = 0; i < gamesJsonArray.length(); i++) {
                games.add(gameFromJson(gamesJsonArray.getJSONObject(i)));
            }

            return games;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<Game>();
        }
    }

    private HttpURLConnection openGetConnection(final String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        return connection;
    }
}
